package com.xkdx.guangguang.fragment.home;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.xkdx.caipiao.HomePageActivity;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.HomeActivity;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.adapter.HomeAdapter;
import com.xkdx.guangguang.adapter.HomeImageAdapter;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.city.CityFragment;
import com.xkdx.guangguang.fragment.home.HomeModule.HomeInfo;
import com.xkdx.guangguang.fragment.my.setup.UpdateVerisonAction;
import com.xkdx.guangguang.fragment.my.setup.UpdateVersionModule;
import com.xkdx.guangguang.fragment.my.setup.UpdateVersionModule.Startup;
import com.xkdx.guangguang.fragment.my.setup.UpdateVersionPresistener;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.shareclass.DiscountInfo;
import com.xkdx.guangguang.util.SharePrefenceUtil;
import com.xkdx.guangguang.wiget.CustomListView;

public class HomeFragment extends BaseFragment implements OnScrollListener,
		OnClickListener {
	private View view;
	private HomeModule module;
	private HomeAction actions;
	private Button refresh_btn, nearlocation, city_btn;
	private HomePresenter presenter;
	private ListView touchPart;
	private CustomListView first, second;
	private CustomListView imageListView;
	private List<HomeInfo> single;
	private List<HomeInfo> list = new ArrayList<HomeInfo>();
	private List<DiscountInfo> nearByList;
	private TextView shop_redshownum;
	private LinearLayout ll_discout;
	private String cityName;
	private SharePrefenceUtil su_city;
	private UpdateVersionPresistener updateVersionPresistener;
	private UpdateVerisonAction updateVerisonAction;
	private UpdateVersionModule updateVersionModule;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		su_city = new SharePrefenceUtil(getActivity(), IConstants.SP_CITY);
		checkVersion();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.home, container, false);
		findView();
		setOnClick();
		showLoading();
		return view;
	}

	@Override
	public void findView() {
		first = (CustomListView) view.findViewById(R.id.second_listview);
		second = (CustomListView) view.findViewById(R.id.third_listview);
		imageListView = (CustomListView) view.findViewById(R.id.first_listview);
		refresh_btn = (Button) view.findViewById(R.id.home_refresh);
		shop_redshownum = (TextView) view.findViewById(R.id.shop_redshownum);
		ll_discout = (LinearLayout) view.findViewById(R.id.ll_dicount);
		nearlocation = (Button) view.findViewById(R.id.home_nearlocation); // 附近按钮
		city_btn = (Button) view.findViewById(R.id.home_city);

		actions = new HomeAction();
		module = new HomeModule();
	}

	@Override
	public void showLoading() {
		presenter = new HomePresenter(this);
		((ManagerActivity) getActivity()).addCurrentTask(presenter);
		dataLoadDialog.show();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				presenter.cancel(true);
			}
		});
		presenter.setActitons(actions);
		presenter.setModule(module);
		presenter.execute();
	}

	private void setListValuse() {

		for (int i = 0; i < 20; i++) {
			Iterator<HomeInfo> it = single.iterator();
			while (it.hasNext()) {
				list.add(it.next());
			}
		}
		// Log.i("HomeActivity", "list.size-->" + list.size());

		HomeAdapter homeAdapter1 = new HomeAdapter(getActivity(), list, false,
				first, second, imageListView);
		first.setAdapter(homeAdapter1);
		HomeAdapter homeAdapter2 = new HomeAdapter(getActivity(), list, true,
				first, second, imageListView);
		second.setAdapter(homeAdapter2);
		HomeImageAdapter imageAdapter = new HomeImageAdapter(getActivity(),
				list, imageListView);
		imageListView.setAdapter(imageAdapter);

		first.setSelection(list.size() / 2);
		second.setSelection(list.size() / 2);
		imageListView.setSelection(list.size() / 2);
		first.setOnScrollListener(HomeFragment.this);
		second.setOnScrollListener(HomeFragment.this);
		imageListView.setOnScrollListener(HomeFragment.this);

	}

	public void startTouch(CustomListView paramCustomListView) {
		// Log.i(TAG, "StartTouch");
		this.touchPart = paramCustomListView;
	}

	public void handleFling(ListView paramListView) {
		View localView = null;
		if (touchPart != null) {
			localView = this.touchPart.getChildAt(0);
		}
		if (localView == null) {
			return;
		}

		if (paramListView == imageListView) {
			int m = 0 - localView.getTop();
			int n = -m;
			if (m > localView.getHeight() / 2) {
				n = localView.getHeight() - m;
			}

			this.touchPart = null;
			imageListView.smoothScrollBy(n, 500);
			int i1 = (int) (n / 2.5);
			first.smoothScrollBy(i1, 500);
			second.smoothScrollBy(i1, 500);
		}
		if (paramListView == first) {
			int m = 0 - localView.getTop();
			int n = -m;
			if (m > localView.getHeight() / 2) {
				n = localView.getHeight() - m;
			}
			int i1 = (int) (n * 2.5);
			this.touchPart = null;
			imageListView.smoothScrollBy(i1, 500);
			first.smoothScrollBy(n, 500);
			second.smoothScrollBy(n, 500);
		}
		if (paramListView == second) {
			int m = 0 - localView.getTop();
			int n = -m;
			if (m > localView.getHeight() / 2) {
				n = localView.getHeight() - m;
			}
			int i1 = (int) (n * 2.5);
			this.touchPart = null;
			imageListView.smoothScrollBy(i1, 500);
			first.smoothScrollBy(n, 500);
			second.smoothScrollBy(n, 500);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (firstVisibleItem >= (list.size() - single.size())
				|| firstVisibleItem <= single.size()) {
			first.setSelection(list.size() / 2);
			second.setSelection(list.size() / 2);
			imageListView.setSelection(list.size() / 2);
		}

		if (view != touchPart) {
			return;
		}
		int j = 0;
		int k = 0;
		int m = 0;
		int i = touchPart.getFirstVisiblePosition();
		if (touchPart.getChildAt(0) != null) {
			j = touchPart.getChildAt(0).getTop();
			k = (int) (touchPart.getChildAt(0).getTop() * 2.5);
			m = (int) (touchPart.getChildAt(0).getTop() / 2.5);
		}
		if (view == first) {
			second.setSelectionFromTop(i, j);
			imageListView.setSelectionFromTop(i, k);

		}
		if (view == second) {
			first.setSelectionFromTop(i, j);
			imageListView.setSelectionFromTop(i, k);
		}
		if (view == imageListView) {
			first.setSelectionFromTop(i, m);
			second.setSelectionFromTop(i, m);
		}

	}

	@Override
	public void showClick(HashMap<String, AbsModule> msg) {
		dataLoadDialog.dismiss();
		if (msg.containsKey("0")) {
			HomeModule homeModule = (HomeModule) msg.get("0");
			single = homeModule.list;
			nearByList = homeModule.nearInfoList;
			setListValuse();
			ll_discout.setVisibility(View.VISIBLE);
			shop_redshownum.setText(nearByList.size() + "");
			((HomeActivity) getActivity()).setHomeModule(homeModule);

		} else {
			showErrorTip(msg);
		}

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setOnClick() {

		refresh_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				showLoading();
				
				//测试彩票
				Intent intent = new Intent(getActivity(),HomePageActivity.class);
				startActivity(intent);
				
			}
		});

		// 附近1000米的优惠信息
		nearlocation.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (View.VISIBLE == ll_discout.getVisibility()) {
					ll_discout.setVisibility(View.INVISIBLE);
					FragmentTransaction ft = getFragmentManager()
							.beginTransaction();
					DayRecommendFragment nearByFragment = new DayRecommendFragment();
					ft.replace(R.id.fragment, nearByFragment);
					ft.addToBackStack(null);
					ft.commit();
				}
			}
		});

		city_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				CityFragment cityFragment = new CityFragment();
				getFragmentManager().beginTransaction()
						.replace(R.id.fragment, cityFragment)
						.addToBackStack(null).commit();

			}
		});
//		start_game.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				Intent intent = new Intent(getActivity(), BhgActivity.class);
//				startActivity(intent);
//			}
//		});

	}

	@Override
	public void onStart() {
		String choiceCityName = su_city.getChoiceCityName();
		String locationCityName = su_city.getLocationCityName();
		if (choiceCityName.equals("")) {
			city_btn.setText(locationCityName);
		} else {
			city_btn.setText(su_city.getChoiceCityName());
		}

		super.onStart();
	}

	private void checkVersion() {
		updateVerisonAction = new UpdateVerisonAction(getActivity());
		updateVersionModule = new UpdateVersionModule();
		updateVersionPresistener = new UpdateVersionPresistener(this);
		updateVersionPresistener.setActitons(updateVerisonAction);
		updateVersionPresistener.setModule(updateVersionModule);
		updateVersionPresistener.execute();
	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		if (map.containsKey("0")) {
			final Startup startup = updateVersionModule.startup;
			if (startup.getClientUpdate().equals("True")) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						getActivity());
				builder.setTitle("有新版本,是否更新");
				builder.setNegativeButton("是",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								IConstants.download(getActivity(),startup
										.getClientDownloadUrl());
							}
						});
				builder.setPositiveButton("否", null);
				builder.create().show();
			}

		}

	}

}
